package middleware

import (
	"sort"
	"sync"

	"github.com/gogf/gf/v2/net/ghttp"
)

type MiddlewareModel struct {
	middleware ghttp.HandlerFunc
	sort       int
}

var (
	middlewares []MiddlewareModel
	once        sync.Once
)

// RegisterMiddleware 注册中间件（线程安全）
func RegisterMiddleware(middleware ghttp.HandlerFunc, sort int) {
	once.Do(func() {
		middlewares = make([]MiddlewareModel, 0)
	})
	middlewares = append(middlewares, MiddlewareModel{
		middleware: middleware,
		sort:       sort,
	})
}

// GetMiddlewares 获取所有已注册的中间件
func GetMiddlewares() []ghttp.HandlerFunc {
	// 创建全局中间件的副本用于排序
	sorted := make([]MiddlewareModel, len(middlewares))
	copy(sorted, middlewares)

	// 按 sort 字段从小到大排序
	sort.Slice(sorted, func(i, j int) bool {
		return sorted[i].sort < sorted[j].sort
	})

	// 提取中间件处理函数
	result := make([]ghttp.HandlerFunc, len(sorted))
	for i, mw := range sorted {
		result[i] = mw.middleware
	}
	return result
}
